<template>
  <div style="display: flex; justify-content: center; align-items: center">
    <div
      style="
        min-width: 900px;
        width: 900px;
        background-color: #fff;
        margin-top: 20px;
        padding: 20px;
        height: calc(100vh - 140px);
        overflow-y: auto;
      "
    >
      <!-- 页面预览 -->
      <div id="printBox1" ref="pdfContent" v-loading="loading">
        <div>
          <div
            style="padding: 0px 0; margin: 0 0px; position: relative"
            ref="tableAll"
            id="table1"
          >
            <div style="position: relative; height: 90px">
              <img
                src="@/assets/images/screen/jtlogo_sm.png"
                width="150"
                style="position: absolute; left: 0px; top: 5px"
              />
              <div
                style="
                  font-size: 22px;
                  display: flex;
                  justify-content: center;
                  margin-bottom: 10px;
                  margin-top: 0px;
                "
              >
                <div class="box1">
                  <span style="font-size: 20px; line-height: 26px">
                    Dalian Giantech Automobile Parts Co., Ltd.</span
                  >
                  <span style="font-size: 20px; line-height: 26px">
                    X光探伤</span
                  >
                  <span style="font-size: 20px; line-height: 26px">
                    X-ray detection</span
                  >
                </div>
              </div>
              <!-- 送货单基本信息 -->
              <div
                style="
                  display: flex;
                  margin-bottom: 2px;
                  font-size: 15px;
                  font-weight: 400;
                  color: #6e7073;
                  margin-top: -20px;
                "
              >
                <div style="flex: 1"></div>
                <div style="flex: 1">
                  <div style="text-align: right">
                    NO:{{ formData?.No || "" }}
                  </div>
                </div>
              </div>
            </div>

            <table
              border="1"
              cellpadding="0"
              cellspacing="0"
              align="center"
              class="dashed-border"
            >
              <colgroup>
                <col width="120" />
                <col width="120" />
                <col width="120" />
                <col width="120" />
                <col width="120" />
                <col width="120" />
              </colgroup>
              <tbody>
                <tr class="tr_1">
                  <td colspan="1">
                    <div class="box1">
                      <div>报告编号</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Supplier
                      </div>
                    </div>
                  </td>
                  <td colspan="5">
                    <div class="box1" style="font-size: 16px">
                      {{ formData?.reportCode || "" }}
                    </div>
                  </td>
                </tr>
                <tr class="tr_2">
                  <td colspan="1">
                    <div class="box1">
                      <div>客户</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Customer
                      </div>
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      {{ formData?.customerName || "" }}
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      <div>产品图号</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Drawing No.
                      </div>
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      {{ formData?.materialDrawingNo || "" }}
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      <div>零件名称</div>
                      <div>Part Name</div>
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      {{ formData?.materialName || "" }}
                    </div>
                  </td>
                </tr>

                <tr class="tr_3">
                  <td colspan="1">
                    <div class="box1">
                      <div>材质</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Material
                      </div>
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      {{ formData?.materialQuality || "" }}
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      <div>产品批号</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Product No.
                      </div>
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      {{ formData?.materialBatch || "" }}
                    </div>
                  </td>
                  <td colspan="1" v-if="cols.length > 0">
                    <div class="box1">
                      <div>{{ cols[0].name }}</div>
                      <div style="font-size: 13px; line-height: 20px">
                        {{ cols[0].code }}
                      </div>
                    </div>
                  </td>
                  <td colspan="1" v-if="cols.length > 0">
                    <div class="box1">
                      {{ cols[0].content }}
                    </div>
                  </td>
                </tr>
                <tr
                  class="tr_info"
                  v-for="(row, rowIndex) in generateRows(cols)"
                  :key="rowIndex"
                >
                  <template v-for="(col, colIndex) in row" :key="colIndex">
                    <td colspan="1">
                      <div class="box1">
                        <div>{{ col.name }}</div>
                        <div style="font-size: 13px; line-height: 20px">
                          {{ col.code }}
                        </div>
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        {{ col.content }}
                      </div>
                    </td>
                  </template>
                </tr>
                <tr style="line-height: 0" class="tr_4">
                  <td colspan="1">
                    <div class="box1">
                      <div>验收标准</div>
                    </div>
                  </td>
                  <td colspan="5" style="line-height: 0">
                    <div
                      style="
                        min-height: 180px;
                        max-height: 300px;
                        line-height: 0;
                      "
                    >
                      <img
                        v-if="formData.images && formData.images.length > 0"
                        :src="`${upPreviewUrl}/${formData.images[0].url}`"
                        width="100%"
                        style="max-height: 300px"
                      />
                    </div>
                  </td>
                </tr>
                <tr class="tr_5">
                  <td colspan="1">
                    <div class="box1">
                      <div>验收结论</div>
                    </div>
                  </td>
                  <td colspan="5">
                    <div class="box1" style="min-height: 100px">
                      {{ formData?.acceptanceConclusion || "" }}
                    </div>
                  </td>
                </tr>
                <tr class="tr_6">
                  <td colspan="1">
                    <div class="box1">
                      <div>位置</div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      <div>图片</div>
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      <div>位置</div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      <div>图片</div>
                    </div>
                  </td>
                </tr>
                <tr v-if="groupedData.length === 0">
                  <td colspan="12" style="height: 90px"></td>
                </tr>
                <template v-else>
                  <tr
                    v-for="(row, rowIndex) in groupedData"
                    :key="rowIndex"
                    class="tr_item"
                  >
                    <template v-for="(item, colIndex) in row" :key="colIndex">
                      <td colspan="1">
                        <div class="box1">
                          <div>{{ item?.sopItemName || "" }}</div>
                          <div style="font-size: 13px; line-height: 20px">
                            {{
                              item.sopItemResult === "1"
                                ? "(合格)"
                                : item.sopItemResult === "0"
                                ? "(不合格)"
                                : ""
                            }}
                          </div>
                        </div>
                      </td>
                      <td colspan="2" style="line-height: 0">
                        <!-- <span
                          v-for="(item1, index) in item?.images"
                          :key="index"
                        > -->
                        <span
                          v-for="(item1, index) in item?.images"
                          :key="index"
                          style="
                            width: 50%;
                            display: inline-block;
                            text-align: center;
                          "
                        >
                          <img
                            :src="`${upPreviewUrl}${item1.url}`"
                            style="
                              width: 100px;
                              height: 100px;
                              margin: 3px;
                              cursor: pointer;
                            "
                            @click="
                              handlePictureCardPreview(
                                `${upPreviewUrl}${item1.url}`
                              )
                            "
                            alt=""
                          />
                        </span>
                      </td>
                    </template>
                  </tr>
                </template>

                <tr>
                  <td colspan="1">
                    <div class="box1">
                      <div>检验员</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Inspector
                      </div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      {{ formData?.inspector || "" }}
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      <div>核准签发</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Review
                      </div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      {{ formData?.approveUserName || "" }}
                    </div>
                  </td>
                </tr>
                <tr>
                  <td colspan="1">
                    <div class="box1">
                      <div>检验日期</div>
                      <div style="font-size: 13px; line-height: 20px">Date</div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      {{ formData?.inspectDate || "" }}
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      <div>审核签发日期</div>
                      <div style="font-size: 13px; line-height: 20px">
                        DateDate
                      </div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      {{ formData?.approveDate || "" }}
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>

            <!-- 信息提示区域 -->
          </div>
        </div>
      </div>

      <!-- 打印、pdf预览 -->
      <div id="printBox" ref="pdfContent" v-show="startPdf">
        <!-- 循环生成第几页 page-break为打印分页标识-->
        <div
          v-for="(pageItem, pageIndex) in groupList"
          :key="pageIndex"
          :class="pageIndex === 0 ? '0' : 'page-break'"
          style="height: 1070px; position: relative; width: 750px"
        >
          <!-- <el-divider border-style="dashed" style="margin: 20px 0" /> -->
          <div style="position: relative" ref="tableAll" id="table1">
            <div style="position: relative; height: 90px">
              <img
                src="@/assets/images/screen/jtlogo_sm.png"
                width="150"
                style="position: absolute; left: 0px; top: 5px"
              />
              <div
                style="
                  font-size: 22px;
                  display: flex;
                  justify-content: center;
                  margin-bottom: 10px;
                  margin-top: 0px;
                "
              >
                <div class="box1">
                  <span style="font-size: 20px; line-height: 26px">
                    Dalian Giantech Automobile Parts Co., Ltd.</span
                  >
                  <span style="font-size: 20px; line-height: 26px">
                    X光探伤</span
                  >
                  <span style="font-size: 20px; line-height: 26px">
                    X-ray detection</span
                  >
                </div>
              </div>
              <!-- 送货单基本信息 -->
              <div
                style="
                  display: flex;
                  margin-bottom: 2px;
                  font-size: 15px;
                  font-weight: 400;
                  color: #6e7073;
                  margin-top: -20px;
                "
              >
                <div style="flex: 1"></div>
                <div style="flex: 1">
                  <div style="text-align: right">
                    NO:{{ formData?.No || "" }}
                  </div>
                </div>
              </div>
            </div>

            <table
              border="1"
              cellpadding="0"
              cellspacing="0"
              align="center"
              class="dashed-border"
              style="
                border-collapse: collapse; /* 使边框合并为单一边框 */
                border: 1px solid #333;
              "
            >
              <colgroup>
                <col width="120" />
                <col width="120" />
                <col width="120" />
                <col width="120" />
                <col width="120" />
                <col width="120" />
              </colgroup>
              <tbody>
                <template v-if="pageIndex === 0">
                  <tr class="">
                    <td colspan="1">
                      <div class="box1">
                        <div>报告编号</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Supplier
                        </div>
                      </div>
                    </td>
                    <td colspan="5">
                      <div class="box1" style="font-size: 16px">
                        {{ formData?.reportCode || "" }}
                      </div>
                    </td>
                  </tr>
                  <tr class="">
                    <td colspan="1">
                      <div class="box1">
                        <div>客户</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Customer
                        </div>
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        {{ formData?.customerName || "" }}
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        <div>产品图号</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Drawing No.
                        </div>
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        {{ formData?.materialDrawingNo || "" }}
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        <div>零件名称</div>
                        <div>Part Name</div>
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        {{ formData?.materialName || "" }}
                      </div>
                    </td>
                  </tr>

                  <tr class="">
                    <td colspan="1">
                      <div class="box1">
                        <div>材质</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Material
                        </div>
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        {{ formData?.materialQuality || "" }}
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        <div>产品批号</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Product No.
                        </div>
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        {{ formData?.materialBatch || "" }}
                      </div>
                    </td>
                    <td colspan="1" v-if="cols.length > 0">
                      <div class="box1">
                        <div>{{ cols[0].name }}</div>
                        <div style="font-size: 13px; line-height: 20px">
                          {{ cols[0].code }}
                        </div>
                      </div>
                    </td>
                    <td colspan="1" v-if="cols.length > 0">
                      <div class="box1">
                        {{ cols[0].content }}
                      </div>
                    </td>
                  </tr>
                  <tr
                    class=""
                    v-for="(row, rowIndex) in generateRows(cols)"
                    :key="rowIndex"
                  >
                    <template v-for="(col, colIndex) in row" :key="colIndex">
                      <td colspan="1">
                        <div class="box1">
                          <div>{{ col.name }}</div>
                          <div style="font-size: 13px; line-height: 20px">
                            {{ col.code }}
                          </div>
                        </div>
                      </td>
                      <td colspan="1">
                        <div class="box1">
                          {{ col.content }}
                        </div>
                      </td>
                    </template>
                  </tr>
                  <tr style="line-height: 0" class="">
                    <td colspan="1">
                      <div class="box1">
                        <div>验收标准</div>
                      </div>
                    </td>
                    <td colspan="5" style="line-height: 0">
                      <div
                        style="
                          min-height: 180px;
                          max-height: 300px;
                          line-height: 0;
                        "
                      >
                        <img
                          v-if="formData.images && formData.images.length > 0"
                          :src="`${upPreviewUrl}/${formData.images[0].url}`"
                          width="100%"
                          style="max-height: 300px"
                        />
                      </div>
                    </td>
                  </tr>
                  <tr class="">
                    <td colspan="1">
                      <div class="box1">
                        <div>验收结论</div>
                      </div>
                    </td>
                    <td colspan="5">
                      <div class="box1" style="min-height: 100px">
                        {{ formData?.acceptanceConclusion || "" }}
                      </div>
                    </td>
                  </tr>
                  <tr class="">
                    <td colspan="1">
                      <div class="box1">
                        <div>位置</div>
                      </div>
                    </td>
                    <td colspan="2">
                      <div class="box1">
                        <div>图片</div>
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        <div>位置</div>
                      </div>
                    </td>
                    <td colspan="2">
                      <div class="box1">
                        <div>图片</div>
                      </div>
                    </td>
                  </tr>
                </template>
                <tr v-if="pageItem.noItem">
                  <td colspan="12" style="height: 90px"></td>
                </tr>
                <template v-else>
                  <tr
                    v-for="(row, rowIndex) in pageItem?.itemListTable"
                    :key="rowIndex"
                    class=""
                  >
                    <template v-for="(item, colIndex) in row" :key="colIndex">
                      <td colspan="1">
                        <div class="box1">
                          <div>{{ item?.sopItemName || "" }}</div>
                          <div style="font-size: 13px; line-height: 20px">
                            {{
                              item.sopItemResult === "1"
                                ? "(合格)"
                                : item.sopItemResult === "0"
                                ? "(不合格)"
                                : ""
                            }}
                          </div>
                        </div>
                      </td>
                      <td colspan="2" style="line-height: 0">
                        <!-- <span
                          v-for="(item1, index) in item?.images"
                          :key="index"
                        > -->
                        <span
                          v-for="(item1, index) in item?.images"
                          :key="index"
                          style="
                            width: 50%;
                            display: inline-block;
                            text-align: center;
                          "
                        >
                          <img
                            :src="`${upPreviewUrl}${item1.url}`"
                            style="
                              width: 100px;
                              height: 100px;
                              margin: 3px;
                              cursor: pointer;
                            "
                            @click="
                              handlePictureCardPreview(
                                `${upPreviewUrl}${item1.url}`
                              )
                            "
                            alt=""
                          />
                        </span>
                      </td>
                    </template>
                  </tr>
                </template>

                <tr v-if="pageItem.showSummary1">
                  <td colspan="1">
                    <div class="box1">
                      <div>检验员</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Inspector
                      </div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      {{ formData?.inspector || "" }}
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      <div>核准签发</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Review
                      </div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      {{ formData?.approveUserName || "" }}
                    </div>
                  </td>
                </tr>
                <tr v-if="pageItem.showSummary2">
                  <td colspan="1">
                    <div class="box1">
                      <div>检验日期</div>
                      <div style="font-size: 13px; line-height: 20px">Date</div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      {{ formData?.inspectDate || "" }}
                    </div>
                  </td>
                  <td colspan="1">
                    <div class="box1">
                      <div>审核签发日期</div>
                      <div style="font-size: 13px; line-height: 20px">
                        DateDate
                      </div>
                    </div>
                  </td>
                  <td colspan="2">
                    <div class="box1">
                      {{ formData?.approveDate || "" }}
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div
            style="
              position: absolute;
              width: 100%;
              text-align: center;
              bottom: 0;
              left: 0;
              font-size: 12px;
            "
          >
            当前页：{{ pageIndex + 1 }}，总计：{{ groupList.length }}
          </div>
        </div>
      </div>
    </div>
    <div class="flex flex-col ml-3">
      <div>
        <el-button type="primary" @click="startPrint" class="mb-2 w-[96px]"
          >打 印</el-button
        >
      </div>

      <div>
        <el-button type="primary" @click="downloadPDF" class="mb-2 w-[96px]"
          >下载 PDF</el-button
        >
      </div>

      <div>
        <el-button @click="previewPDF" class="mb-2 w-[96px]"
          >预览 PDF</el-button
        >
      </div>
    </div>
    <el-dialog
      v-model="pdfPreviewDialog"
      title="PDF 预览"
      width="1100"
      :close-on-click-modal="false"
      draggable
      alignCenter
      class="printDialog"
    >
      <div style="height: 650px">
        <div v-if="pdfPreviewUrl" style="height: 650px">
          <embed
            :src="pdfPreviewUrl"
            type="application/pdf"
            style="width: 100%; height: 100%"
          />
        </div>
        <div v-else>正在生成预览，请稍候...</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import dayjs from "dayjs";
import html2pdf from "./components/PDFs";
import html2pdfs from "html2pdf.js";
import printJS from "print-js";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { useRoute, useRouter } from "vue-router";
import { useReportModelConfigStore } from "../pinia/ReportModelConfigStore";
import { deepClone } from "@/utils/commonHooks";

const route = useRoute();
const router = useRouter();

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSXRAYINSPECTIONREPORT",
  inheritAttrs: false,
});

const emit = defineEmits(["change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

watch(
  () => props.data,
  (newVal: any) => {
    if (newVal?.id) {
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
}

const loading = ref(false);

// 时间转换
function formatDate(dateString: string | number | Date) {
  if (dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}年${month}月${day}日`;
  } else {
    return `   年  月  日`;
  }
}

const uploadApi = import.meta.env.VITE_APP_BASE_API;
// 预览url前缀
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;

const handlePictureCardPreview = (url: string) => {
  url = url?.replace("fileCenter/download/", "fileCenter/preview/");
  window.open(url);
};

const tableAll = ref(null);
function PDFprit() {
  let tableAll1 = tableAll.value;
  let title = "X光检验报告";

  // html2pdf(table, {
  //   background: "#fff",
  //   minimumUnit: "tr",
  //   orientation: "l",
  // });
  html2pdf("table1", title, dayjs(new Date()).format("YYYY-MM-DD"));
  // console.log("printData.value", tableAll.value.scrollWidth);

  // generatePdf(tableAll.value, "报告标题");
}

const downloadPDF = () => {
  startPdf.value = true;
  const element = pdfContent.value;
  html2pdfs()
    .set(pdfOptions)
    .from(element)
    .save()
    .finally(() => {
      startPdf.value = false;
    });
};

// 打印数据
const printData = ref<any>();

const getDetail = async () => {
  loading.value = true;
  console.log("props.id", props.data.id);
  await request({
    url: `/qms/q8dqualityproblem/get/${props.data.id}`,
    method: "get",
    data: {},
  })
    .then((res) => {
      if (res.data != null) {
        printData.value = res.data;
        console.log("printData.value", printData.value);

        loading.value = false;
      } else {
        loading.value = false;
      }
    })
    .finally(() => {
      loading.value = false;
    });

  // setTimeout(() => {
  //   printData.value = mock;
  //   loading.value = false;
  // }, 500);
};

const startPdf = ref(false);
// 开始打印
function startPrint() {
  startPdf.value = true;
  // 开始打印
  setTimeout(() => {
    printJS({
      printable: "printBox", // 打印内容的容器 id
      type: "html", // 打印类型
      imageStyle: "",
      scanStyles: false,
      style: `
     @media print {
        @page {
          margin: 7mm 5mm;
        }
        body {
          margin: 0;
        }
        div,
        table,
        tr,
        td,
        th,
        tbody,
        thead,
        span,
        image {
          padding: 0;
          margin: 0;
        }
        .page-break {
          page-break-before: always;
        }
        .dashed-border {
          width: 100%;
          border-collapse: collapse; /* 使边框合并为单一边框 */
          border: 1px solid #333;
        }

        .dashed-border td,
        .dashed-border th {
          font-size: 13px;
          border: 1px solid #333;
          min-height: 30px;
          padding: 4px 6px;
          overflow-wrap: anywhere;
          line-height: 20px;
          word-break: break-all;
        }

        tr {
          page-break-inside: avoid;
        }

        .bold td {
          font-weight: 600;
          text-align: center;
        }

        td {
          text-align: center;
        }

        .left td {
          text-align: left;
        }

        .box1 {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }

        .box1 div:nth-child(1) {
          font-size: 14px;
        }
        .box1 div:nth-child(2) {
          line-height: 20px;
          font-size: 13px;
        }
      }
    `,
    });
    startPdf.value = false;
  }, 500);
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// onMounted(async () => {
//   if (route?.query.id) {
//     loading.value = true;
//     await getDetail1(route?.query.id);
//   }

//   fillData();
// });
// onActivated(() => {
//   fillData();
// });

onActivated(() => {
  groupList_1.value = [
    {
      page: 1,
      itemList: [],
      itemListTable: [],
      showImageTitle: false,
    },
  ];

  groupList.value = [
    {
      page: 1,
      itemList: [],
      itemListTable: [],
      showImageTitle: false,
    },
  ];

  if (route.query.id) {
    getDetail();
  } else {
    formData.value = {};
  }
  fillData();
});

const fillData = async () => {
  const reportStore = useReportModelConfigStore();

  const previewData = reportStore.previewData;
  if (previewData) {
    console.log("从store接收到的formData:", previewData);

    await getReportTemplate(previewData.reportTemplateId);
    formData.value.images = previewData.images;
    formData.value.customerName = previewData.customerName;
    formData.value.materialDrawingNo = previewData.materialDrawingNo;
    formData.value.materialBatch = previewData.materialBatch;
    formData.value.materialName = previewData.materialName;
    if (previewData.details && previewData.details.length > 0) {
      const checkItemIds = previewData.details.map((item) => item.checkItemId);
      Promise.all(
        checkItemIds.flatMap(async (item) => {
          const { data } = await getCheckItem(item);
          return data;
        })
      )
        .then((data) => {
          formData.value.checkOrderDetails = data.flat();
        })
        .finally(() => {
          setTimeout(() => {
            computedHeight();
          }, 800);
        });
    }
    if (previewData.reportDetails && previewData.reportDetails.length > 0) {
      formData.value.checkOrderDetails = previewData.reportDetails;
    }
    // reportStore.clearPreviewData();
  } else {
    cols.value = [];
    Object.assign(formData.value, formDataInit);
    setTimeout(() => {
      computedHeight();
    }, 800);
  }
};

const groupedData = computed(() => {
  let rows = [];
  if (
    formData.value?.checkOrderDetails &&
    formData.value?.checkOrderDetails.length > 0
  ) {
    for (let i = 0; i < formData.value?.checkOrderDetails.length; i += 2) {
      rows.push(formData.value?.checkOrderDetails.slice(i, i + 2));
    }
  }
  return rows;
});

const getCheckItem = async (checkItemId: any[] = []) => {
  return await request({
    url: `/qms/qmssopitem/getListByCheckItemId`,
    method: "post",
    data: { checkItemId },
  });
};

const getDetail1 = async (id) => {
  await request({
    url: `/qms/qmsreportrecord/report/query?reportRecordId=${id}`,
    method: "get",
  }).then((res) => {
    if (res.data != null) {
      // formData.value = res.data;
      formData.value = Object.assign(formData.value, res.data);
      console.log("formData.value", formData.value);
      loading.value = false;
      // setTimeout(() => {
      //   computedHeight();
      // }, 200);
    } else {
      loading.value = false;
    }
  });
};

const cols = ref([]);

const getReportTemplate = async (id) => {
  await request({
    url: `qms/qmsreporttemplate/getDetails`,
    method: "post",
    data: { id },
  }).then((res) => {
    if (res.data != null) {
      cols.value = res.data;
      loading.value = false;
    } else {
      loading.value = false;
    }
  });
};

const mock1 = ref([
  {
    id: "1963081208941309953",
    createTime: "2025-09-03 11:26:47",
    lastUpdateTime: "2025-09-03 11:26:47",
    createdUserId: "1",
    lastUpdatedUserId: "1",
    createdUserName: "管理员",
    lastUpdatedUserName: "管理员",
    version: 1,
    sopItemId: "1963073071098163202",
    fileType: "jpg",
    path: "test/info",
    originalfilename: "icon09.jpg",
    filename: "1963081163761389568.jpg",
    url: "test/info/1963081163761389568.jpg",
    remarks: null,
    enabled: null,
    deleted: 0,
    ids: null,
  },
  {
    id: "1963081208945504257",
    createTime: "2025-09-03 11:26:47",
    lastUpdateTime: "2025-09-03 11:26:47",
    createdUserId: "1",
    lastUpdatedUserId: "1",
    createdUserName: "管理员",
    lastUpdatedUserName: "管理员",
    version: 1,
    sopItemId: "1963073071098163202",
    fileType: "jpg",
    path: "test/info",
    originalfilename: "004.jpg",
    filename: "1963081200180531200.jpg",
    url: "test/info/1963081200180531200.jpg",
    remarks: null,
    enabled: null,
    deleted: 0,
    ids: null,
  },
]);
const formData = ref({
  reportRecordId: "",
  reportCategory: "",
  reportCode: "",
  customerName: "",
  materialDrawingNo: "",
  materialCode: "",
  materialName: "",
  materialQuality: "",
  materialBatch: "",
  deviceType: "",
  checkLevel: "",
  voltage: "",
  electric: "",
  resolution: "",
  imageQualityMeter: "",
  imageQualitySensi: "",
  inspector: "",
  inspectDate: "",
  approveUserName: "",
  approveDate: null,
  checkOrderDetails: [],
  images: [],
  image: [],
  acceptanceConclusion: null,
  acceptanceCriteria: null,
  comprehensiveJudgment: "",
});

const formDataInit = {
  reportRecordId: "",
  reportCategory: "",
  reportCode: "",
  customerName: "",
  materialDrawingNo: "",
  materialCode: "",
  materialName: "",
  materialQuality: "",
  materialBatch: "",
  deviceType: "",
  checkLevel: "",
  voltage: "",
  electric: "",
  resolution: "",
  imageQualityMeter: "",
  imageQualitySensi: "",
  inspector: "",
  inspectDate: "",
  approveUserName: "",
  approveDate: null,
  checkOrderDetails: [],
  images: [],
  image: [],
  acceptanceConclusion: null,
  acceptanceCriteria: null,
  comprehensiveJudgment: "",
};
const pdfContent = ref(null);
const pdfPreviewDialog = ref(false);
const pdfPreviewUrl = ref<any>(null);

const exportPDF = () => {
  // 同上述代码
};

const pdfOptions = {
  filename: formData.value?.reportCode
    ? `X射线检验报告(${formData.value?.reportCode})`
    : `X射线检验报告.pdf`, // 指定生成文件的名称
  margin: [6.8, 5],
  image: { type: "jpeg", quality: 2 },
  html2canvas: { scale: 2, useCORS: true, logging: false },
  jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
  splitTextToRows: false, // 关闭文本拆分行
};

const previewPDF = () => {
  startPdf.value = true;
  const element = pdfContent.value;

  if (!element) {
    console.error("Error: pdfContent is not defined or not bound to the DOM.");
    return;
  }

  const container = document.getElementById("printBox");
  if (!container) {
    console.error("Error: #pdf-content element not found in the DOM.");
    return;
  }

  container.classList.add("export");

  pdfPreviewDialog.value = true;
  pdfPreviewUrl.value = null;

  html2pdfs()
    .from(element)
    .set(pdfOptions)
    .toPdf()
    .get("pdf")
    .then((pdf: any) => {
      const pdfBlob = pdf.output("blob");
      pdfPreviewUrl.value = URL.createObjectURL(pdfBlob);
    })
    .finally(() => {
      container.classList.remove("export");
      startPdf.value = false;
    });
};
const generateRows = (data) => {
  const rows = [];
  for (let i = 1; i < data.length; i += 3) {
    rows.push(data.slice(i, i + 3));
  }
  return rows;
};

const groupList_1 = ref<any>([
  {
    page: 1,
    itemList: [],
    itemListTable: [],
    showImageTitle: false,
  },
]);

const groupList = ref<any>([
  {
    page: 1,
    itemList: [], // 检验项
    itemListTable: [],
    showImageTitle: false, // 图片头部
  },
]);

function computedHeight() {
  let totalHeight = 0;
  const headerHeight = 90;
  const tr1Height =
    document.getElementsByClassName("tr_1")?.[0]?.clientHeight ?? 0;
  const tr2Height =
    document.getElementsByClassName("tr_2")?.[0]?.clientHeight ?? 0;
  const tr3Height =
    document.getElementsByClassName("tr_3")?.[0]?.clientHeight ?? 0;

  // 第一页头部高度计算
  totalHeight = headerHeight + tr1Height + tr2Height + tr3Height;

  // 自定义基础信息高度计算
  const infos = document.getElementsByClassName("tr_info");
  if (infos.length) {
    for (let i = 0; i < infos?.length; i++) {
      totalHeight += infos[i]?.clientHeight;
    }
  }

  // 验收标准高度计算
  const tr4Height =
    document.getElementsByClassName("tr_4")?.[0]?.clientHeight ?? 0;
  totalHeight += tr4Height;

  // 验收结论高度计算
  const tr5Height =
    document.getElementsByClassName("tr_5")?.[0]?.clientHeight ?? 0;
  totalHeight += tr5Height;

  // 位置、图片论高度计算
  const tr6Height =
    document.getElementsByClassName("tr_6")?.[0]?.clientHeight ?? 0;
  totalHeight += tr6Height;

  // 判断检验项是否分页
  if (
    formData.value?.checkOrderDetails &&
    formData.value?.checkOrderDetails.length > 0
  ) {
    const itemsList = document.getElementsByClassName("tr_item");
    for (let i = 0; i < itemsList?.length; i++) {
      const item = itemsList[i];
      if (totalHeight + item.clientHeight < 1050) {
        for (let j = 0; j < 2; j++) {
          if (formData.value?.checkOrderDetails[i * 2 + j]) {
            const data1 = deepClone(groupList_1.value);
            data1[data1.length - 1].itemList.push(
              formData.value?.checkOrderDetails[i * 2 + j] ?? {}
            );
            groupList_1.value = deepClone(data1);
          }
        }
        totalHeight += item.clientHeight;
      } else if (totalHeight + item.clientHeight >= 1050) {
        let list2: any = [];

        for (let j = 0; j < 2; j++) {
          list2.push(formData.value?.checkOrderDetails[i * 2 + j] ?? {});
        }
        let data1 = deepClone(groupList_1.value);
        data1.push({
          page: data1[data1.length - 1].page + 1,
          itemList: list2,
          itemListTable: [],
          showImageTitle: false,
        });
        groupList_1.value = deepClone(data1);
        totalHeight = headerHeight + item.clientHeight;
      }
    }
  } else {
    // noItem
    if (totalHeight + 90 < 1050) {
      groupList_1.value[groupList_1.value.length - 1].noItem = true;
      totalHeight += 90;
    } else {
      groupList_1.value.push({
        page: groupList_1.value[groupList_1.value.length - 1].page + 1,
        itemList: [],
        itemListTable: [],
        noItem: true,
      });
      totalHeight = headerHeight + 90;
    }
  }

  // 判断是否有页尾统计第一行
  if (totalHeight + 49 < 1050) {
    groupList_1.value[groupList_1.value.length - 1].showSummary1 = true;
    totalHeight += 49;
  } else {
    groupList_1.value.push({
      page: groupList_1.value[groupList_1.value.length - 1].page + 1,
      itemList: [],
      itemListTable: [],
      showSummary1: true,
    });
    totalHeight = headerHeight + 49;
  }

  // 判断是否有页尾统计第二行
  if (totalHeight + 49 < 1050) {
    groupList_1.value[groupList_1.value.length - 1].showSummary2 = true;
    totalHeight += 49;
  } else {
    groupList_1.value.push({
      page: groupList_1.value[groupList_1.value.length - 1].page + 1,
      itemList: [],
      itemListTable: [],
      showSummary2: true,
    });
    totalHeight = headerHeight + 49;
  }

  groupList.value = filterTable(groupList_1.value);

  console.log(groupList.value);
}

function filterTable(list) {
  const elderlist = list;
  for (let i = 0; i < elderlist.length; i++) {
    const item = elderlist[i];
    // 图片处理 三个一行
    let rows = [];
    const dataImage = JSON.parse(JSON.stringify(item?.itemList || []));
    if (dataImage && dataImage.length > 0) {
      for (let i = 0; i < dataImage.length; i += 2) {
        rows.push(dataImage.slice(i, i + 2));
      }
    }
    elderlist[i].itemListTable = rows;
  }
  return elderlist;
}
</script>

<style lang="scss" scoped>
div,
table,
tr,
td,
th,
tbody,
thead,
span,
image {
  padding: 0;
  margin: 0;
}
.app-container {
  height: inherit;
  overflow: scroll;
  padding: 0;
}

:deep(.printDialog .el-dialog__body) {
  padding: 10px !important;
  height: calc(100vh - 220px);
  overflow: scroll;
}

.dashed-border {
  width: 100%;
  border-collapse: collapse; /* 使边框合并为单一边框 */
  border: 1px solid #333;
}

.dashed-border td,
.dashed-border th {
  color: #333;
  font-size: 13px;
  border: 1px solid #333;
  min-height: 30px;
  padding: 4px 6px;
  overflow-wrap: anywhere;
  line-height: 20px;
  word-break: break-all;
}

tr {
  page-break-inside: avoid;
  border-collapse: collapse; /* 使边框合并为单一边框 */
}

.bold td {
  font-weight: 600;
}

td {
  text-align: center;
  border-collapse: collapse; /* 使边框合并为单一边框 */
}

.left td {
  text-align: left;
}

.box1 {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.box1 div:nth-child(1) {
  font-size: 14px;
}
.box1 div:nth-child(2) {
  line-height: 20px;
  font-size: 13px;
}
</style>
